package com.wiloon.androidx.utils;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.log4j.Logger;
import java.lang.reflect.Type;
import java.util.Date;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;


/**
 * Created by wiloon on 11/26/14.
 */
public class JsonHelper {
    private static final Logger logger = Logger.getLogger(JsonHelper.class);

    public String jacksonTest(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = null;
        try {
            jsonString = mapper.writeValueAsString(obj);
            logger.debug("json string by jackson=" + jsonString);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonString;
    }

    public String fastJsonTest(Object obj) {
        String jsonString = JSON.toJSONString(obj);
        logger.debug("json string by fast json=" + jsonString);
        return jsonString;
    }

    public String gsonTest(Object obj) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        // Register customized DateTypeAdapter
        // set html code disable
        gsonBuilder.disableHtmlEscaping();
        gsonBuilder.registerTypeAdapter(Date.class, new MillisecondsDateTypeAdapter());

        String json = gsonBuilder.create().toJson(obj);
        logger.debug("json string by gson=" + json);
        return json;
    }

    public static class MillisecondsDateTypeAdapter implements com.google.gson.JsonSerializer<Date>, com.google.gson.JsonDeserializer<Date> {

        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src.getTime());
        }

        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return new Date(json.getAsLong());
        }
    }
}
